/**
 * 
 */
package com.example.rabbitmqTest;

import java.text.SimpleDateFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;  
  

@Service  
public class ReceiptService {  
  
    private static final Logger log= LoggerFactory.getLogger(ReceiptService.class);  
  
    private SimpleDateFormat dateFormat=new SimpleDateFormat();  
  
    @Autowired  
    private Environment env;  
  
  
    @Autowired  
    private RabbitTemplate rabbitTemplate;  
  
    @Autowired  
    private ObjectMapper objectMapper;  
  
    /** 
     * 录入收款单 
     * @param addDto 
     * @throws Exception 
     */  
    public void insert(ReceiptAddDto addDto) throws Exception{  
        Receipt entity=new Receipt();  
        BeanUtils.copyProperties(addDto,entity);  
  
        dateFormat=new SimpleDateFormat(env.getProperty("receipt.date.format"));  
        entity.setReceiptDate(dateFormat.parse(addDto.getReceiptDateStr()));  
        log.debug("开始录入收款单，收款单信息： {} ",entity);  
  
        //TODO:更新客户相关信息逻辑：如收款次数、合同信息、地址信息等  
  
        //TODO:真正的录入收款单记录1-dao层操作  
  
        //TODO:真正的录入收款单记录1-mq操作-异步，解耦先有业务模块的整体逻辑，降低整个业务模块的响应速度  
        Message message= MessageBuilder.withBody(objectMapper.writeValueAsBytes(entity)).build();  
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());  
  
        //方式一：  
        /*rabbitTemplate.setExchange(env.getProperty("mq.second.queue.exchange")); 
        rabbitTemplate.setRoutingKey(env.getProperty("mq.second.queue.routingKey")); 
        rabbitTemplate.send(message);*/  
  
        //方式二：exchange+routingKey 携带着消息 -> 队列 ->进行监听消费  
        rabbitTemplate.convertAndSend(env.getProperty("mq.second.queue.exchange"),env.getProperty("mq.second.queue.routingKey"),"队列1");  
        rabbitTemplate.convertAndSend("exchange2","routingkey2","队列2");  
        
    }  
  
}  